package com.jplayground.tree;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.util.List;
import java.io.IOException;

/**
 * @author Natalia Batishcheva
 * @project JPlayground
 * @data: 05.01.2008
 */
public class TreeTag extends TagSupport {
    private TreeNodeVO tree;
    private String styleId;

    public TreeNodeVO getTree() {
        return tree;
    }

    public void setTree(TreeNodeVO tree) {
        this.tree = tree;
    }

    public String getStyleId() {
        return styleId;
    }

    public void setStyleId(String styleId) {
        this.styleId = styleId;
    }

    public int doStartTag() throws JspException {
        try {
            final JspWriter out = pageContext.getOut();

            out.print("<ul id=\"" + styleId + "\" class=\"filetree\">");
            renderTree(tree);
            out.print("</ul>");

            return TagSupport.SKIP_BODY;

        } catch (IOException e) {
            throw new JspException("IO Exception");
        }
    }

    private void renderTree(TreeNodeVO node) throws IOException {
        final JspWriter out = pageContext.getOut();

        if (node.isLeaf()) {
            out.println("<li>");
            out.println("<span class=\"file\" id=\"" + node.getId() + "\">" + node.getName() + "</span>");
            out.println("</li>");

        } else {
            out.println("<li>");
            out.println("<span class=\"folder\" id=\"" + node.getId() + "\">" + node.getName() + "</span>");

            final List<TreeNodeVO> subNodes = node.getSubNodes();
            if (subNodes != null && !subNodes.isEmpty()) {
                out.println("<ul>");
                for (TreeNodeVO subNode : node.getSubNodes()) {
                    renderTree(subNode);
                }
                out.println("</ul>");
            }

            out.println("</li>");
        }
    }
}